package repositories

import (
	"errors"
	"fox/db"
	"fox/models"
	request2 "fox/request"
	response2 "fox/response"
	"gorm.io/gorm"
	"math"
)

type PermissionRepository struct {
}

func NewPermissionRepository() (permissionRepository *PermissionRepository) {
	return &PermissionRepository{}
}

func (repository *PermissionRepository) InsertPermission(permission *models.Permission) (id int64, err error) {
	var (
		result *gorm.DB
	)

	result = db.GDatabase.Db.Create(permission)
	if result.RowsAffected == 1 {
		return permission.ID, err
	}
	return 0, result.Error
}

func (repository *PermissionRepository) DeletePermissionById(id int64) (err error) {
	var (
		result *gorm.DB
	)

	result = db.GDatabase.Db.Delete(&models.Permission{ID: id})
	if result.RowsAffected == 1 && result.Error == nil {
		return err
	}
	return result.Error
}

func (repository *PermissionRepository) UpdatePermissionById(permission *models.Permission) (newPermission *models.Permission, err error) {
	var (
		result *gorm.DB
	)

	result = db.GDatabase.Db.Model(&models.Permission{ID: permission.ID}).UpdateColumns(permission)
	result.Scan(&newPermission)
	return newPermission, result.Error

}

func (repository *PermissionRepository) SelectPermissionById(id int64) (permission *models.Permission, err error) {
	var (
		result *gorm.DB
	)

	result = db.GDatabase.Db.Where("id = ?", id).First(&permission)
	if result.RowsAffected == 1 {
		return permission, nil
	}
	if result.RowsAffected == 0 {
		return nil, errors.New("没有查找到记录")
	}
	return permission, result.Error
}

func (repository *PermissionRepository) SelectPermissions(permission *request2.Permission) (result *response2.Result, err error) {
	var (
		offset          int
		permissions     *[]models.Permission
		countPermission *models.Permission
		count           int64
		totalPage       int
	)
	countPermission = new(models.Permission)
	count = repository.CountPermissions(countPermission)
	if count == 0 {
		result.Total = 0
		result.Size = permission.Size
		result.Page = permission.Page
		result.Lists = make([]interface{}, 0)
		return result, err
	}

	totalPage = int(math.Ceil(float64(count) / float64(permission.Size)))
	offset = (permission.Page - 1) * permission.Size
	db.GDatabase.Db.Scopes(request2.Paginate(offset, permission.Size)).Model(&models.Permission{}).Order(permission.SortField + " " + permission.Sort).Find(&permissions)
	return &response2.Result{
		Total:     count,
		TotalPage: totalPage,
		Page:      permission.Page,
		Size:      permission.Size,
		Lists:     permissions,
	}, err
}

func (repository *PermissionRepository) CountPermissions(permission *models.Permission) (count int64) {

	db.GDatabase.Db.Model(&models.Permission{}).Count(&count)
	return count
}
